package com.example.dirviesystem.student.controller;

import com.example.dirviesystem.entity.PracticeRecord;
import com.example.dirviesystem.entity.SimulateExamRecord;
import com.example.dirviesystem.repository.PracticeRecordRepository;
import com.example.dirviesystem.repository.SimulateExamRepository;
import com.example.dirviesystem.student.service.StudentExamService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/exam")
@RequiredArgsConstructor
public class StudentExamController {

    private final StudentExamService examService;
    private final SimulateExamRepository simulateExamRepository;
    private final PracticeRecordRepository practiceRecordRepository;

    @PostMapping("/practice")
    public ResponseEntity<?> savePractice(
            @RequestParam Long studentId,
            @RequestParam Long questionId,
            @RequestParam String answer
    ) {
        examService.savePracticeRecord(studentId, questionId, answer);
        return ResponseEntity.ok("保存成功");
    }
    @GetMapping("/practice/answers")
    public ResponseEntity<?> getPracticeAnswers(
            @RequestParam Long studentId,
            @RequestParam String subject
    ) {
        return ResponseEntity.ok(examService.getPracticeAnswers(studentId, subject));
    }


    @PostMapping("/simulate/start")
    public ResponseEntity<?> startSimulate(
            @RequestParam Long studentId,
            @RequestParam String subject
    ) {
        SimulateExamRecord exam = examService.startSimulateExam(studentId, subject);
        return ResponseEntity.ok(exam);
    }

    @PostMapping("/simulate/submit")
    public ResponseEntity<?> submitSimulate(
            @RequestParam Long examId,
            @RequestParam int correctCount,
            @RequestParam int totalQuestions,
            @RequestParam int score
    ) {
        SimulateExamRecord result = examService.submitSimulateExam(examId, correctCount, totalQuestions, score);
        return ResponseEntity.ok(result);
    }

    @GetMapping("/simulate/avg")
    public ResponseEntity<?> getAvgScore(
            @RequestParam Long studentId,
            @RequestParam String subject
    ) {
        double avg = examService.getAverageScore(studentId, subject);
        return ResponseEntity.ok(avg);
    }

    @GetMapping("/simulate/exam-records/{studentId}")
    public Map<String,Object> getSimulateExamRecords(
            @PathVariable Long studentId,
            @RequestParam String subject
    ) {
        List<SimulateExamRecord> records= simulateExamRepository.findByStudentIdAndSubject(studentId, subject);
        double average=records.stream()
                .mapToInt(SimulateExamRecord::getScore)
                .average()
                .orElse(0.0);

        Map<String,Object> result = new HashMap<>();
        result.put("average", average);
        result.put("records", records);
        return result;
    }

    @GetMapping("/simulate/pending")
    public ResponseEntity<?> getPendingSimulateExam(
            @RequestParam Long studentId,
            @RequestParam String subject
    ) {
        Optional<SimulateExamRecord> optionalExam = examService.getPendingSimulateExam(studentId, subject);
        if (optionalExam.isPresent()) {
            return ResponseEntity.ok(Map.of(
                    "hasPending", true,
                    "examId", optionalExam.get().getId()
            ));
        } else {
            return ResponseEntity.ok(Map.of(
                    "hasPending", false
            ));
        }
    }
    @GetMapping("/simulate/progress")
    public ResponseEntity<?> getSimulateProgress(@RequestParam Long examId) {
        // 获取考试记录
        SimulateExamRecord exam = simulateExamRepository.findById(examId)
                .orElseThrow(() -> new RuntimeException("考试记录不存在"));

        if (exam.isSubmitted()) {
            return ResponseEntity.badRequest().body("该考试已提交");
        }

        Long studentId = exam.getStudent().getId();
        String subject = exam.getSubject();

        // 查询该学生该科目的答题记录（可加 examId 判断更精准）
        List<PracticeRecord> records = practiceRecordRepository.findByStudentIdAndSubject(studentId, subject);

        // 计算剩余时间（最多30分钟）
        long elapsedSeconds = java.time.Duration.between(exam.getStartTime(), LocalDateTime.now()).getSeconds();
        long timeLeft = Math.max(1800 - elapsedSeconds, 0);

        // 返回答题记录和剩余时间
        return ResponseEntity.ok(
                Map.of(
                        "answers", records,
                        "timeLeft", timeLeft
                )
        );
    }

}
